﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using FBroSharp;
using FBroSharp.Lib;
using FBroSharp.Value;
using FBroSharp.DataType;
using OfficeOpenXml;

namespace 文件上传助手
{
    public partial class Form1 : Form
    {
        // 常量定义
        private const string BROWSER_USER_FLAG = "upload_browser";
        private const string UPLOAD_URL = "https://zh-cn.imgbb.com/";
        private static readonly string[] SUPPORTED_FORMATS = { ".jpg", ".jpeg", ".png", ".bmp", ".gif", ".tif", ".tiff", ".webp", ".heic", ".avif", ".pdf" };
        private const long MAX_FILE_SIZE = 32 * 1024 * 1024; // 32 MB

        // 上传队列
        private Queue<string> uploadQueue = new Queue<string>();
        private bool isUploading = false;
        private bool isPageReady = false;
        private string currentUploadingFile = null;

        public Form1()
        {
            InitializeComponent();
            
            // 设置 EPPlus 许可证（非商业用途）
            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            UpdateStatus("正在初始化浏览器...");
            CreateBrowser();
        }

        /// <summary>
        /// 创建浏览器实例
        /// </summary>
        private void CreateBrowser()
        {
            try
            {
                // 创建浏览器事件处理器
                BrowserEvent browserEvent = new BrowserEvent(this);

                // 配置窗口信息（嵌入式浏览器）
                FBroSharpWindowsInfo windowInfo = new FBroSharpWindowsInfo
                {
                    parent_window = panelBrowser.Handle,
                    x = 0,
                    y = 0,
                    width = panelBrowser.Width,
                    height = panelBrowser.Height,
                    window_name = "ImgBB 上传浏览器"
                };

                // 创建浏览器设置
                FBroSharpBrowserSetting settings = new FBroSharpBrowserSetting();

                // 创建浏览器
                bool success = FBroSharpControl.CreatBrowser(
                    UPLOAD_URL,
                    windowInfo,
                    settings,
                    null,  // request_context
                    null,  // extra_info
                    browserEvent,
                    default,  // event_control (struct 类型使用 default)
                    BROWSER_USER_FLAG
                );

                if (!success)
                {
                    UpdateStatus("❌ 浏览器创建失败！");
                    MessageBox.Show("浏览器创建失败，请检查 FBro 框架是否正确初始化。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    UpdateStatus("浏览器创建成功，正在加载页面...");
                }
            }
            catch (Exception ex)
            {
                UpdateStatus($"❌ 创建浏览器时出错: {ex.Message}");
                MessageBox.Show($"创建浏览器时出错：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 获取浏览器实例
        /// </summary>
        private IFBroSharpBrowser GetBrowser()
        {
            var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
            if (browser == null || !browser.IsValid)
            {
                UpdateStatus("❌ 浏览器实例无效！");
                return null;
            }
            return browser;
        }

        /// <summary>
        /// 页面加载完成回调
        /// </summary>
        public void OnPageLoadComplete()
        {
            if (InvokeRequired)
            {
                Invoke(new Action(OnPageLoadComplete));
                return;
            }

            isPageReady = true;
            btnAddFiles.Enabled = true;
            btnImportExcel.Enabled = true;
            btnStartUpload.Enabled = listViewFiles.Items.Count > 0;
            UpdateStatus("✅ 页面已就绪，可以开始添加文件");
        }

        /// <summary>
        /// 添加单个文件
        /// </summary>
        private void btnAddFiles_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Title = "选择要上传的文件";
                ofd.Filter = "支持的图片格式|*.jpg;*.jpeg;*.png;*.bmp;*.gif;*.tif;*.tiff;*.webp;*.heic;*.avif;*.pdf|所有文件|*.*";
                ofd.Multiselect = true;

                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    AddFilesToList(ofd.FileNames);
                }
            }
        }

        /// <summary>
        /// 从 Excel 导入文件路径
        /// </summary>
        private void btnImportExcel_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Title = "选择 Excel 文件";
                ofd.Filter = "Excel 文件|*.xlsx;*.xls|所有文件|*.*";
                ofd.Multiselect = false;

                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    ImportFromExcel(ofd.FileName);
                }
            }
        }

        /// <summary>
        /// 从 Excel 导入文件路径列表
        /// </summary>
        private void ImportFromExcel(string excelPath)
        {
            try
            {
                List<string> filePaths = new List<string>();

                using (var package = new ExcelPackage(new FileInfo(excelPath)))
                {
                    var worksheet = package.Workbook.Worksheets[0]; // 读取第一个工作表
                    int rowCount = worksheet.Dimension.Rows;

                    for (int row = 1; row <= rowCount; row++)
                    {
                        var cellValue = worksheet.Cells[row, 1].Value?.ToString();
                        if (!string.IsNullOrWhiteSpace(cellValue))
                        {
                            filePaths.Add(cellValue.Trim());
                        }
                    }
                }

                if (filePaths.Count > 0)
                {
                    AddFilesToList(filePaths.ToArray());
                    UpdateStatus($"从 Excel 导入了 {filePaths.Count} 个文件路径");
                }
                else
                {
                    MessageBox.Show("Excel 文件中没有找到有效的文件路径。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导入 Excel 文件失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 添加文件到列表
        /// </summary>
        private void AddFilesToList(string[] files)
        {
            int addedCount = 0;
            int skippedCount = 0;

            foreach (string filePath in files)
            {
                // 验证文件
                if (!File.Exists(filePath))
                {
                    skippedCount++;
                    continue;
                }

                FileInfo fileInfo = new FileInfo(filePath);

                // 检查文件大小
                if (fileInfo.Length > MAX_FILE_SIZE)
                {
                    skippedCount++;
                    continue;
                }

                // 检查文件格式
                string ext = fileInfo.Extension.ToLower();
                if (!SUPPORTED_FORMATS.Contains(ext))
                {
                    skippedCount++;
                    continue;
                }

                // 检查是否已存在
                bool exists = false;
                foreach (ListViewItem item in listViewFiles.Items)
                {
                    if (item.Tag?.ToString() == filePath)
                    {
                        exists = true;
                        break;
                    }
                }

                if (!exists)
                {
                    ListViewItem item = new ListViewItem(fileInfo.Name);
                    item.SubItems.Add(FormatFileSize(fileInfo.Length));
                    item.SubItems.Add("等待上传");
                    item.Tag = filePath;
                    listViewFiles.Items.Add(item);
                    addedCount++;
                }
            }

            if (addedCount > 0)
            {
                btnStartUpload.Enabled = true;
                UpdateStatus($"已添加 {addedCount} 个文件" + (skippedCount > 0 ? $"，跳过 {skippedCount} 个文件" : ""));
            }
            else if (skippedCount > 0)
            {
                UpdateStatus($"所有文件都被跳过（{skippedCount} 个）");
            }
        }

        /// <summary>
        /// 格式化文件大小
        /// </summary>
        private string FormatFileSize(long bytes)
        {
            string[] sizes = { "B", "KB", "MB", "GB" };
            double len = bytes;
            int order = 0;
            while (len >= 1024 && order < sizes.Length - 1)
            {
                order++;
                len = len / 1024;
            }
            return $"{len:0.##} {sizes[order]}";
        }

        /// <summary>
        /// 移除选中的文件
        /// </summary>
        private void btnRemoveFiles_Click(object sender, EventArgs e)
        {
            if (listViewFiles.SelectedItems.Count > 0)
            {
                foreach (ListViewItem item in listViewFiles.SelectedItems)
                {
                    listViewFiles.Items.Remove(item);
                }
                UpdateStatus($"已移除 {listViewFiles.SelectedItems.Count} 个文件");
                btnStartUpload.Enabled = listViewFiles.Items.Count > 0;
            }
        }

        /// <summary>
        /// 清空文件列表
        /// </summary>
        private void btnClearFiles_Click(object sender, EventArgs e)
        {
            listViewFiles.Items.Clear();
            btnStartUpload.Enabled = false;
            UpdateStatus("已清空文件列表");
        }

        /// <summary>
        /// 开始批量上传
        /// </summary>
        private async void btnStartUpload_Click(object sender, EventArgs e)
        {
            if (!isPageReady)
            {
                MessageBox.Show("页面尚未就绪，请稍候再试。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (listViewFiles.Items.Count == 0)
            {
                MessageBox.Show("请先添加要上传的文件。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (isUploading)
            {
                MessageBox.Show("正在上传中，请等待当前上传完成。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // 禁用按钮
            btnStartUpload.Enabled = false;
            btnAddFiles.Enabled = false;
            btnImportExcel.Enabled = false;
            btnStopUpload.Enabled = true;

            // 构建上传队列
            uploadQueue.Clear();
            foreach (ListViewItem item in listViewFiles.Items)
            {
                if (item.SubItems[2].Text != "已完成")
                {
                    uploadQueue.Enqueue(item.Tag.ToString());
                }
            }

            isUploading = true;
            UpdateStatus($"开始批量上传，队列中有 {uploadQueue.Count} 个文件");

            // 开始上传
            await Task.Run(() => ProcessUploadQueue());
        }

        /// <summary>
        /// 停止上传
        /// </summary>
        private void btnStopUpload_Click(object sender, EventArgs e)
        {
            isUploading = false;
            uploadQueue.Clear();
            btnStopUpload.Enabled = false;
            btnStartUpload.Enabled = true;
            btnAddFiles.Enabled = true;
            btnImportExcel.Enabled = true;
            UpdateStatus("已停止上传");
        }

        /// <summary>
        /// 处理上传队列
        /// </summary>
        private void ProcessUploadQueue()
        {
            while (isUploading && uploadQueue.Count > 0)
            {
                currentUploadingFile = uploadQueue.Dequeue();
                
                Invoke(new Action(() =>
                {
                    UpdateFileStatus(currentUploadingFile, "正在上传...");
                    UpdateStatus($"正在上传: {Path.GetFileName(currentUploadingFile)} (剩余 {uploadQueue.Count} 个文件)");
                }));

                // 执行上传
                bool success = UploadFile(currentUploadingFile);

                Invoke(new Action(() =>
                {
                    if (success)
                    {
                        UpdateFileStatus(currentUploadingFile, "已完成");
                        UpdateProgress();
                    }
                    else
                    {
                        UpdateFileStatus(currentUploadingFile, "失败");
                    }
                }));

                // 上传间隔
                Thread.Sleep(2000);
            }

            Invoke(new Action(() =>
            {
                isUploading = false;
                btnStopUpload.Enabled = false;
                btnStartUpload.Enabled = true;
                btnAddFiles.Enabled = true;
                btnImportExcel.Enabled = true;
                UpdateStatus("批量上传完成");
                MessageBox.Show("批量上传任务完成！", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }));
        }

        /// <summary>
        /// 上传单个文件
        /// </summary>
        private bool UploadFile(string filePath)
        {
            try
            {
                var browser = GetBrowser();
                if (browser == null)
                {
                    Console.WriteLine("❌ 浏览器实例无效");
                    return false;
                }

                var frame = browser.GetMainFrame();
                if (frame == null)
                {
                    Console.WriteLine("❌ 浏览器主框架无效");
                    return false;
                }

                Console.WriteLine($"\n========================================");
                Console.WriteLine($"开始上传文件: {Path.GetFileName(filePath)}");
                Console.WriteLine($"文件路径: {filePath}");
                Console.WriteLine($"========================================");

                // ========================================
                // 步骤 1: 使用 JavaScript 获取上传区域的坐标
                // ========================================
                // 注意：文件输入框是隐藏的，应该点击上传区域来触发
                string jsGetPosition = @"
                (function() {
                    // 查找上传区域（整个上传框）
                    var uploadBox = document.getElementById('anywhere-upload');
                    if (!uploadBox) {
                        return JSON.stringify({ success: false, error: '未找到上传区域' });
                    }
                    
                    // 确保上传区域可见
                    uploadBox.classList.remove('upload-box--hidden');
                    
                    // 获取上传区域的位置和尺寸
                    var rect = uploadBox.getBoundingClientRect();
                    var centerX = Math.round(rect.left + rect.width / 2);
                    var centerY = Math.round(rect.top + rect.height / 2);
                    
                    return JSON.stringify({
                        success: true,
                        centerX: centerX,
                        centerY: centerY,
                        width: rect.width,
                        height: rect.height,
                        top: rect.top,
                        isVisible: rect.top >= 0
                    });
                })();
                ";

                // 执行 JavaScript 并获取结果
                var callback = new FBroSharpJsCallbackSyn();
                frame.ExecuteJavaScriptToHasReturn(jsGetPosition, "", 0, callback);

                int centerX = 593; // 默认坐标（上传区域中心）
                int centerY = 537;

                if (callback.help?.IsValid == true)
                {
                    callback.help.WaitEvent(5000);
                    if (callback.help.HavStringData())
                    {
                        string jsonResult = callback.help.GetStringData();
                        Console.WriteLine($"JavaScript 返回结果: {jsonResult}");

                        // 简单解析 JSON（实际应该使用 JSON 库）
                        if (jsonResult.Contains("\"success\":true"))
                        {
                            // 提取 centerX 和 centerY
                            try
                            {
                                int xIndex = jsonResult.IndexOf("\"centerX\":");
                                int yIndex = jsonResult.IndexOf("\"centerY\":");
                                if (xIndex > 0 && yIndex > 0)
                                {
                                    string xPart = jsonResult.Substring(xIndex + 10);
                                    string yPart = jsonResult.Substring(yIndex + 10);
                                    centerX = int.Parse(xPart.Substring(0, xPart.IndexOf(',')));
                                    centerY = int.Parse(yPart.Substring(0, yPart.IndexOf(',')));
                                    Console.WriteLine($"✅ 获取到文件输入框坐标: ({centerX}, {centerY})");
                                }
                            }
                            catch
                            {
                                Console.WriteLine("⚠️ 解析坐标失败，使用默认坐标");
                            }
                        }
                    }
                }

                // ========================================
                // 步骤 2: 设置自动上传文件（OnFileDialog 事件会读取）
                // ========================================
                Console.WriteLine($"设置自动上传文件: {filePath}");
                GlobalUploadManager.SetAutoUploadFile(filePath);

                // ========================================
                // 步骤 3: 使用 VIP 鼠标控制点击文件输入框
                // ========================================
                Console.WriteLine($"使用 VIP 鼠标点击坐标: ({centerX}, {centerY})");

                try
                {
                    var vipControl = browser.GetVIPControl();
                    if (vipControl != null && vipControl.IsValid)
                    {
                        var advanced = vipControl.GetAdvancedControl();
                        if (advanced != null)
                        {
                            // 精准点击：按下 -> 等待 -> 释放
                            Console.WriteLine("执行鼠标按下...");
                            advanced.DispatchMouseDown(centerX, centerY, 0);
                            Thread.Sleep(50);
                            Console.WriteLine("执行鼠标释放...");
                            advanced.DispatchMouseUp(centerX, centerY, 0);
                            Thread.Sleep(500);
                            Console.WriteLine("✅ VIP 鼠标点击完成");
                        }
                        else
                        {
                            Console.WriteLine("❌ VIP Advanced Control 无效");
                        }
                    }
                    else
                    {
                        Console.WriteLine("❌ VIP Control 无效");
                    }
                }
                catch (Exception vipEx)
                {
                    Console.WriteLine($"❌ VIP 鼠标控制失败: {vipEx.Message}");
                }

                // OnFileDialog 事件会自动处理文件选择
                Thread.Sleep(1000); // 等待文件选择完成

                // ========================================
                // 步骤 4: 清除自动上传标志
                // ========================================
                GlobalUploadManager.ClearAutoUpload();
                Console.WriteLine("清除自动上传标志");

                // ========================================
                // 步骤 5: 点击上传按钮（如果需要）
                // ========================================
                // ImgBB 可能会自动开始上传，或需要点击"开始上传"按钮
                // 这里等待一下让文件选择完成
                Thread.Sleep(2000);

                // 可选：检查是否有上传按钮需要点击
                string jsCheckUploadButton = @"
                (function() {
                    var uploadBtn = document.querySelector('[data-action=""upload""]');
                    if (uploadBtn && uploadBtn.offsetParent !== null) {
                        var rect = uploadBtn.getBoundingClientRect();
                        return JSON.stringify({
                            found: true,
                            x: Math.round(rect.left + rect.width / 2),
                            y: Math.round(rect.top + rect.height / 2)
                        });
                    }
                    return JSON.stringify({ found: false });
                })();
                ";

                var uploadBtnCallback = new FBroSharpJsCallbackSyn();
                frame.ExecuteJavaScriptToHasReturn(jsCheckUploadButton, "", 0, uploadBtnCallback);

                if (uploadBtnCallback.help?.IsValid == true)
                {
                    uploadBtnCallback.help.WaitEvent(3000);
                    if (uploadBtnCallback.help.HavStringData())
                    {
                        string btnResult = uploadBtnCallback.help.GetStringData();
                        if (btnResult.Contains("\"found\":true"))
                        {
                            Console.WriteLine("发现上传按钮，准备点击...");
                            // 这里可以再次使用 VIP 鼠标点击上传按钮
                            // 暂时简化，让用户手动观察
                        }
                    }
                }

                // ========================================
                // 步骤 6: 等待上传完成
                // ========================================
                Console.WriteLine("等待上传完成...");
                Thread.Sleep(5000); // 给予足够时间让上传完成

                Console.WriteLine($"✅ 文件上传流程完成: {Path.GetFileName(filePath)}");
                Console.WriteLine($"========================================\n");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 上传文件失败: {ex.Message}");
                Console.WriteLine($"   错误详情: {ex.StackTrace}");
                GlobalUploadManager.ClearAutoUpload();
                return false;
            }
        }

        /// <summary>
        /// 更新文件状态
        /// </summary>
        private void UpdateFileStatus(string filePath, string status)
        {
            foreach (ListViewItem item in listViewFiles.Items)
            {
                if (item.Tag?.ToString() == filePath)
                {
                    item.SubItems[2].Text = status;
                    
                    // 设置颜色
                    if (status == "已完成")
                        item.BackColor = Color.LightGreen;
                    else if (status == "失败")
                        item.BackColor = Color.LightCoral;
                    else if (status == "正在上传...")
                        item.BackColor = Color.LightYellow;
                    
                    break;
                }
            }
        }

        /// <summary>
        /// 更新进度条
        /// </summary>
        private void UpdateProgress()
        {
            int total = listViewFiles.Items.Count;
            int completed = 0;

            foreach (ListViewItem item in listViewFiles.Items)
            {
                if (item.SubItems[2].Text == "已完成")
                {
                    completed++;
                }
            }

            if (total > 0)
            {
                int percentage = (int)((double)completed / total * 100);
                progressBar.Value = percentage;
                lblProgress.Text = $"{completed}/{total} ({percentage}%)";
            }
        }

        /// <summary>
        /// 调整浏览器大小
        /// </summary>
        private void Form1_Resize(object sender, EventArgs e)
        {
            ResizeEmbeddedBrowser();
        }

        private void panelBrowser_Resize(object sender, EventArgs e)
        {
            ResizeEmbeddedBrowser();
        }

        private void ResizeEmbeddedBrowser()
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    browser.MoveWindow(0, 0, panelBrowser.Width, panelBrowser.Height, true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"调整浏览器大小失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新状态栏（线程安全）
        /// </summary>
        public void UpdateStatus(string message)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateStatus(message)));
                return;
            }

            lblStatus.Text = message;
            Console.WriteLine($"[状态] {message}");
        }

        /// <summary>
        /// 更新 URL（线程安全）
        /// </summary>
        public void UpdateUrl(string url)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateUrl(url)));
                return;
            }

            // 可以在这里添加 URL 显示控件
        }

        /// <summary>
        /// 更新标题（线程安全）
        /// </summary>
        public void UpdateTitle(string title)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateTitle(title)));
                return;
            }

            this.Text = $"文件上传助手 - {title}";
        }

        /// <summary>
        /// 窗口关闭时清理资源
        /// </summary>
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    browser.CloseBrowser(true, false);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"关闭浏览器时出错: {ex.Message}");
            }

            base.OnFormClosing(e);
        }
    }
}
